import store from '../store'
import config from '../config'
const requests = {}

const ajax = (params = {}) => {
	return new Promise(async (resolve, reject) => {
		let errMsg = ''
		if (!params.url) {
			errMsg = '请求地址不能为空'
			uni.showModal({
				title: errMsg,
				showCancel: false
			})
			return reject({
				message: errMsg
			})
		}
		// 参数合并
		params = Object.assign({
			method: 'GET',
			baseURL: config.baseURL,
			data: {},
			header: {
				'accessToken': store.state.user.token,
				token: store.state.user.token
			},
			__errorHandle: true, // 自动处理错误
		}, params)
		params.method = params.method.toLocaleUpperCase()
		// 无网络的时候报错	
		if (store.state.event.netWorkType === 'none') {
			errMsg = '无网络连接'
			uni.showToast({
				icon: 'none',
				title: errMsg
			})
			return reject({
				message: errMsg
			})
		}
		// 防抖处理
		if (!['GET', 'OPTIONS'].includes(params.method)) {
			const now = Date.now()
			if (requests[params.url] && now - requests[params.url] <= 100) {
				errMsg = `操作过于频繁${params.url}`
				return reject()
			}
			requests[params.url] = now
		}
		if (!(/:\/\//.test(params.url) || /^\/\//.test(params.url))) {
			params.url = params.baseURL.replace(/\/$/, '') + '/' + params.url.replace(/^\//, '')
		}
		let model = uni.request
		let args = {
			...params,
			data: params.data  // 直接使用原始的 data 对象
		}
		if (params.method === 'UPLOAD') {
			model = uni.uploadFile
			args = {
				...params,
				...params.data
			}
		}
		return model({
			...args,
			success({
				data
			}) {
				if (typeof data === 'string') {
					try {
						data = JSON.parse(data)
					} catch (e) { }
				}
				return resolve(data)
			},
			fail(e) {
				errMsg = e.errMsg
				uni.showToast({
                    icon: 'none',
                    title: errMsg
                })
				return reject({
					message: errMsg
				})
			}
		})
	})
}

['get', 'post', 'put', 'delete', 'head', 'upload'].map(method => {
	ajax[method] = (url, params = {}) => {
		params = Object.assign({
			data: params
		}, {
			url
		}, {
			method: method.toLocaleUpperCase()
		})
		return ajax(params)
	}
})

export default ajax
